<template>
  <div class="article-management-container">
    <div class="page-header">
      <h1>文章管理</h1>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAddArticle">添加文章</el-button>
        <el-button type="primary" @click="handleArticleCategory">管理分类</el-button>
      </div>
    </div>

    <el-card class="article-search-card">
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-form-item label="文章标题">
          <el-input 
            v-model="searchForm.title" 
            placeholder="请输入文章标题"
            @keyup.enter="handleSearch"
            @clear="resetSearch"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" class="status-select" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="已发布" value="Published"></el-option>
            <el-option label="草稿" value="Draft"></el-option>
            <el-option label="已归档" value="Archived"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间区间">
          <el-date-picker 
            v-model="searchForm.dateRange" 
            type="daterange" 
            range-separator="至" 
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="article-table-card" v-loading="loading">
      <el-table ref="articleTable" :data="articleTableData" row-key="id" border
        @selection-change="handleSelectionChange" @row-click="handleRowClick">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="文章标题" min-width="200">
          <template #default="{ row }"><a href="#" @click.prevent="handleViewArticle(row)">{{ row.title
          }}</a></template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120"></el-table-column>
        <el-table-column prop="authorName" label="作者" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="200">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" link @click="handleViewArticle(row)">查看</el-button>
            <el-button size="small" link @click="handleEditArticle(row.id)">编辑</el-button>
            <el-button size="small" link @click="handleDeleteArticle(row.id)" class="text-danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

          <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </el-card>

    <!-- 添加/编辑文章对话框 -->
    <el-dialog v-model="articleDialogVisible" :title="isEditMode ? '编辑文章' : '添加文章'" :width="'800px'"
      :before-close="handleDialogClose">
      <el-form ref="articleFormRef" :model="articleForm" :rules="articleFormRules" label-width="100px"
        class="article-form">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" maxlength="100"></el-input>
        </el-form-item>

        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="articleForm.categoryId" placeholder="请选择文章分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name"
              :value="category.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章摘要" prop="summary">
          <el-input v-model="articleForm.summary" type="textarea" :rows="rows[0]" placeholder="请输入文章摘要"></el-input>
        </el-form-item>

        <el-form-item label="文章内容" prop="content">
          <el-input v-model="articleForm.content" type="textarea" :rows="rows[1]" placeholder="请输入文章内容"></el-input>
          <!-- 实际项目中可替换为富文本编辑器 -->
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="articleForm.status">
            <el-radio  :value="status[0]">草稿</el-radio>
            <el-radio :value="status[1]">已发布</el-radio>
            <el-radio :value="status[2]">已归档</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="articleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitArticleForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 文章查看对话框 -->
    <el-dialog v-model="viewArticleDialogVisible" title="文章详情" :width="'800px'">
      <div v-if="currentArticle" class="article-detail">
        <h2 class="article-detail-title">{{ currentArticle.title }}</h2>
        <div class="article-meta">
          <span>分类: {{ currentArticle.categoryName }}</span>
          <span>作者: {{ currentArticle.authorName }}</span>
          <span>发布日期: {{ formatDate(currentArticle.createdAt) }}</span>
          <span>浏览量:{{ getRandomNumber() }}</span>
        </div>
        <div class="article-summary"><strong>摘要:</strong> {{ currentArticle.summary }}</div>
        <div class="article-content"><strong>正文:</strong> {{ currentArticle.content }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useArticleStore } from '@/stores/article';
import router from '@/router';
// 状态管理
const articleTableData = ref([]);
const selectedArticleId = ref('');
const currentArticle = ref(null);
const articleDialogVisible = ref(false);
const viewArticleDialogVisible = ref(false);
const isEditMode = ref(false);
const articleFormRef = ref(null);
const useStore = useArticleStore()
const displayData = ref([])
const isSearching = ref(false) // 跟踪是否正在搜索状态
const currentSearchForm = ref({}) // 当前搜索条件
const loading = ref(false) // 加载状态
// 搜索表单
const searchForm = reactive({
  title: '',
  status: '',
  dateRange: []
});
const rows=ref([4,10])
// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 文章表单数据
const articleForm = reactive({
  id: null,
  title: '',
  categoryId: null,
  authorName: '',
  summary: '',
  content: '',
  status: null,
});
const status = ref([0,1,2]
)
// 文章分类选项
const getCategories = async () => {
  const response = (await useStore.articleCategories()).articlecategories
  return response
}
//分类管理
const handleArticleCategory = () => {
  router.push('/content/articlecategory')
}
const categories = ref([]);
//浏览量随机数模拟
function getRandomNumber() {
  // 生成一个在 [min, max] 范围内的随机整数
  return Math.floor(Math.random() * (2000 - 300 + 1)) + 300;
}
// 表单验证规则
const articleFormRules = reactive({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '文章标题长度在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  summary: [
    { required: true, message: '请输入文章摘要', trigger: 'blur' },
    { min: 10, max: 500, message: '文章摘要长度在 10 到 500 个字符之间', trigger: 'blur' }
  ]
});
//格式化日期
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};

// 状态处理函数
const getStatusText = (status) => {
  // 支持枚举和字符串两种格式
  if (typeof status === 'number') {
    switch (status) {
      case 0: return '草稿';
      case 1: return '已发布';
      case 2: return '已归档';
      default: return '未知';
    }
  } else if (typeof status === 'string') {
    switch (status) {
      case 'Draft': return '草稿';
      case 'Published': return '已发布';
      case 'Archived': return '已归档';
      default: return status;
    }
  }
  return '未知';
};

const getStatusType = (status) => {
  // 支持枚举和字符串两种格式
  if (typeof status === 'number') {
    switch (status) {
      case 0: return 'info';    // 草稿
      case 1: return 'success'; // 已发布
      case 2: return 'danger';  // 已归档
      default: return '';
    }
  } else if (typeof status === 'string') {
    switch (status) {
      case 'Draft': return 'info';
      case 'Published': return 'success';
      case 'Archived': return 'danger';
      default: return '';
    }
  }
  return '';
};
// 生命周期钩子
onMounted(() => {
  fetchArticleData();
  getCategories();
});

// 获取文章数据
const fetchArticleData = async () => {
  try {
    loading.value = true;
    let response;
    if (isSearching.value) {
      // 如果正在搜索状态，使用搜索API
      response = await useStore.searchArticles(currentSearchForm.value, {
        page: pagination.value.currentPage,
        pageSize: pagination.value.pageSize
      });
    } else {
      // 否则使用普通获取API
      response = await useStore.articleList({
        page: pagination.value.currentPage,
        pageSize: pagination.value.pageSize
      });
    }
    
    articleTableData.value = response.articles;
    displayData.value = [...articleTableData.value]
    pagination.value = response.pagination;
  } catch (error) {
    console.error('获取文章数据失败:', error);
    ElMessage.error('获取文章数据失败');
  } finally {
    loading.value = false;
  }
}

// 处理搜索
async function handleSearch() {
  try {
    loading.value = true;
    isSearching.value = true;
    currentSearchForm.value = { ...searchForm };
    pagination.value.currentPage = 1; // 重置到第一页
    
    const response = await useStore.searchArticles(searchForm, {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    });
    
    articleTableData.value = response.articles;
    displayData.value = [...articleTableData.value];
    pagination.value = response.pagination;
    
    ElMessage.success('搜索完成');
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
}
// 处理分页大小变化
function handleSizeChange(size) {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  fetchArticleData();
}

// 处理页码变化
function handleCurrentChange(page) {
  pagination.value.currentPage = page;
  fetchArticleData();
}

// 处理行点击
function handleRowClick(row) {
  selectedArticleId.value = row.id;
}

// 处理选择变化
function handleSelectionChange(selection) {
  if (selection.length > 0) {
    selectedArticleId.value = selection[0].id;
  } else {
    selectedArticleId.value = '';
  }
}

// 处理添加文章
const handleAddArticle = async () => {

  categories.value = await getCategories()

  isEditMode.value = false;
  // 重置表单
  articleForm.id = null;
  articleForm.title = '';
  articleForm.categoryId = null;
  articleForm.summary = '';
  articleForm.content = '';
  articleForm.status = null;
  articleDialogVisible.value = true;
}
// 处理编辑文章
const handleEditArticle = async (id) => {
  categories.value = await getCategories()

  if (!id && !selectedArticleId.value) return;
  const articleId = id || selectedArticleId.value;
  isEditMode.value = true;

  // 查找文章
  const article = articleTableData.value.find(item => item.id === articleId);
  const filteredId = categories.value.find(item => item.name === article.categoryName)?.id; // 过滤出符合条件的对象
  console.log(filteredId);
  const res =await useArticleStore().singlearticle(article.id);
  
  if (article) {
    // 填充表单
    articleForm.id = article.id;
    articleForm.title = article.title;
    articleForm.categoryId =filteredId
    articleForm.authorName = article.authorName;
    articleForm.status = article.status;
    articleForm.viewCount = article.viewCount;
    articleForm.summary = article.summary;
    articleForm.content = res.content;
    articleDialogVisible.value = true;
  }
}

// 处理删除文章√
function handleDeleteArticle(id) {
  const articleId = id || selectedArticleId.value;
  if (!articleId) return;

  ElMessageBox.confirm('确定要删除这篇文章吗？此操作不可撤销。', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API请求
    setTimeout(async () => {
      // 从表格数据中删除文章
      await useArticleStore().deleteArticle(id);
      ElMessage.success('文章删除成功');
      fetchArticleData()
    }, 300);
  }).catch(() => {
    // 用户取消删除
  });
}

// 处理查看文章
async function handleViewArticle(article) {
  const res =await useArticleStore().singlearticle(article.id);
  article.content=res.content
  console.log(res);
  
  console.log(article.content);
  
  currentArticle.value = { ...article};
  viewArticleDialogVisible.value = true;
}

// 提交文章表单
async function submitArticleForm() {
  if (!articleFormRef.value) return;

  try {
    await articleFormRef.value.validate();
    // 模拟API请求
    setTimeout(async () => {
      if (isEditMode.value) {
        // 编辑文章逻辑
        const id = articleForm.id
        if (id) {

          const response = await useArticleStore().updateArticle(articleForm.id, {
            title: articleForm.title,
            content: articleForm.content,
            summary: articleForm.summary,
            categoryId: articleForm.categoryId,
            status: articleForm.status
          })
          console.log({
            title: articleForm.title,
            content: articleForm.content,
            summary: articleForm.summary,
            categoryId: articleForm.categoryId,
            status:articleForm.status
          });

          console.log(response);
        }
        ElMessage.success('文章编辑成功');
        fetchArticleData()
      } else {
        // 添加文章逻辑
        const newArticle = {
          ...articleForm
        };
        try {
          const response = await useArticleStore().addArticle({
            title: articleForm.title,
            content: articleForm.content,
            summary: articleForm.summary,
            categoryId: articleForm.categoryId,
            status:articleForm.status
          });

          articleTableData.value.unshift(newArticle);
          // pagination.total = articleTableData.value.length;
          ElMessage.success('文章添加成功');
          fetchArticleData()
        } catch (error) {
          ElMessage.error(error)
        }

      }

      articleDialogVisible.value = false;
      selectedArticleId.value = '';
    }, 500);
  } catch (error) {
    // 表单验证失败
    ElMessage.error(error)
    return false;
  }
}

// 处理对话框关闭
function handleDialogClose(done) {
  ElMessageBox.confirm('确定要取消吗？未保存的内容将丢失。').then(() => {
    done();
  }).catch(() => {
    // 不关闭对话框
  });
}

// 重置搜索
function resetSearch() {
  searchForm.title = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  isSearching.value = false;
  currentSearchForm.value = {};
  pagination.value.currentPage = 1;
  fetchArticleData();
}
</script>

<style scoped>
.article-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.article-search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.article-form {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}

.article-detail {
  padding: 10px 0;
}

.article-detail-title {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.article-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
  justify-content: center;
}

.article-summary {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.article-content {
  line-height: 1.8;
}

.status-select {
  width: 130px;
}
</style>